import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit'

let initialState = {
  count: 0,
  user: {
    name: 'nick',
    phone: 123,
  },
  loading: false
}

const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state, { payload }) => {
      state.count += payload
    },
    decrement: state => {
      state.count -= 5
    },
    setLoading: (state, { payload }) => {
      state.loading = payload
    }
  },
})

export const { increment, decrement, setLoading } = counterSlice.actions;

function delay (time=1000) {
  return new Promise((r) => {
    setTimeout(() => {
      r(true)
    }, time)
  })
}

// 异步方法
export const increAsync = (payload=0) => async (dispatch, getState) => {
  const { app: { count } } = getState();
  dispatch(setLoading(true))
  await delay(1000)
  dispatch(increment(payload - 5));
  dispatch(setLoading(false))
};

export default counterSlice.reducer
